const qiniu = require("qiniu");
const uuidv4 = require("uuid").v4;

const {
  QINIU_ACCESS_KEY,
  QINIU_SECRET_KEY,
  QINIU_BUCKET,
  QINIU_DOMAIN,
} = require("../../config/config.default");
const { uploadFileSuccess } = require("../../constant/success.type");
const { uploadError } = require("../../constant/err.type");
class CommonController {
  async uploadFile(ctx, nuxt) {
    if (ctx.request.files==undefined) {
      ctx.body = uploadError;
      ctx.app.emit("error", uploadError, ctx);
    } else {
      //需要填写你的 Access Key 和 Secret Key
      qiniu.conf.ACCESS_KEY = QINIU_ACCESS_KEY;
      qiniu.conf.SECRET_KEY = QINIU_SECRET_KEY;
      const mac = new qiniu.auth.digest.Mac(QINIU_ACCESS_KEY, QINIU_SECRET_KEY);
      //要上传的空间
      const bucket = QINIU_BUCKET;
      //上传到七牛后保存的文件名
      const uuid = uuidv4();
      const key = `${uuid}-${ctx.request.files.file.originalFilename}`;
      //构建上传策略函数
      function uptoken(bucket, key) {
        try {
          const options = {
            scope: bucket + ":" + key,
            expires: 86400,
          };
          // 使用模板字符串来确保bucket和key中的特殊字符被正确处理
          const putPolicy = new qiniu.rs.PutPolicy(options);
          return putPolicy.uploadToken(mac);
          // 此处可以添加更多逻辑，比如使用putPolicy进行进一步的操作
          console.log("PutPolicy成功构造:", putPolicy);
        } catch (error) {
          // 对于任何构造或操作中的错误，都应该进行适当的处理
          // 在这里，我们简单地记录错误。实际应用中可能需要更复杂的错误处理逻辑
          console.error("构造PutPolicy时发生错误:", error);

          // 根据错误的类型和业务需求，可能需要抛出错误或进行其他错误处理
        }
      }
      //生成上传 Token
      const uploadToken = uptoken(bucket, key);

      const config = new qiniu.conf.Config();
      const formUploader = new qiniu.form_up.FormUploader(config);
      const putExtra = new qiniu.form_up.PutExtra();
      const localFile = ctx.request.files.file.filepath;
      // 文件上传

      const qiniuRequest = await formUploader
        .putFile(uploadToken, key, localFile, putExtra)
        .then(({ data, resp }) => {
          if (resp.statusCode === 200) {
            return `${QINIU_DOMAIN}${data.key}`;
          } else {
            console.log(resp.statusCode);
            console.log(data);
          }
        })
        .catch((err) => {
          console.log("------------");
          console.log(err);
          console.log("------------");
        });
      // 文件上传
      uploadFileSuccess.result = qiniuRequest;
      ctx.body = uploadFileSuccess;
    }
  }
}

module.exports = new CommonController();
